/**********************************************
 * Author: ideawu(www.ideawu.net)
 * Date: 2007-04
 * File: server.c
 *********************************************/

#include "tftpx.h"
#include "work_thread.h"

// Max request datagram size
#define MAX_REQUEST_SIZE 1024


int main (int argc, char **argv){
	int sock;
	int done = 0;	// Server exit.
	socklen_t addr_len;
	pthread_t t_id;
	struct sockaddr_in server;
	unsigned short port = 69;
	conf_document_root = ".";

	printf("使用方式: %s [port]\n", argv[0]);
	printf("默认端口69\n");

	if(argc == 2)
	{
		port = (unsigned short)atoi(argv[1]);
	}
	else if(argc>2)
	{
		printf("错误：参数过多\n");
		return -1;
	}
	
	if((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
		printf("Server socket could not be created.\n");
		return 0;
	}
	
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = port;

	if (bind(sock, (struct sockaddr *) &server, sizeof(server)) < 0){
		printf("Server bind failed. Server already running? Proper permissions?\n");
		return 2;
	}
	
	printf("Server started at 0.0.0.0:%d in current directory.\n",port);
	
	struct tftpx_request *request;
	addr_len = sizeof(struct sockaddr_in);
	while(!done){
		request = (struct tftpx_request *)malloc(sizeof(struct tftpx_request));
		memset(request, 0, sizeof(struct tftpx_request));
		request->size = recvfrom(
				sock, &(request->packet), MAX_REQUEST_SIZE, 0,
				(struct sockaddr *) &(request->client),
				&addr_len);
		request->packet.cmd = ntohs(request->packet.cmd);
		printf("Receive request.\n");
		if(pthread_create(&t_id, NULL, work_thread, request) != 0){
			printf("Can't create thread.\n");
		}
	}

	return 0;
}
